﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace MusicPlow
{
    public class Youtube
    {
        const string c_getTitleFormat = "http://gdata.youtube.com/feeds/api/videos/{0}?v=2&alt=jsonc";
        const string c_getDirectLinkFormat = "http://gdata.youtube.com/feeds/api/videos?max-results={0}&v=2&alt=json&category=Music&q={1}&key={2}";
        const string c_youTubeDeveloperKey = "AI39si7ItKx6A8QBt4TEsrU9gmRXghP9B9Z_MMEgECXO9dGzipKBngYO2nhMDw36YcNgbaAif---9di22Aim6e43DC5874Q9MA";

        public static Task<TimedOperation<string>> GetTitle(string id)
        {
            DateTime startTime = DateTime.Now;
            return WebRequestExtensions.ExecuteJsonWebRequestTask<TimedOperation<string>>(string.Format(c_getTitleFormat,
                HttpUtility.UrlEncode(id)),
                ytresult => 
                    {
                        TimeSpan runTime = DateTime.Now - startTime;
                        return new TimedOperation<string>(ytresult["data"]["title"], runTime);
                    });
        }

        public static Task<TimedOperation<string>> GetSongFromText(string artistName, string songName)
        {
            string searchString = HttpUtility.UrlEncode(string.Format("{0} {1}", artistName, songName));

            return GetSongsFromText(searchString, 1).ContinueWith<TimedOperation<string>>(t =>
                {
                    if (t.Result.Result != null &&
                        t.Result.Result.Any() &&
                        string.IsNullOrEmpty(t.Result.Result.First()) == false)
                    {
                        return new TimedOperation<string>(t.Result.Result.First(), t.Result.RunTime);
                    }
                    else
                    {
                        return new TimedOperation<string>(string.Format(
                                "http://www.youtube.com/results?search_type=videos&search_category=10&uni=3&search_query={0}",
                                searchString), t.Result.RunTime);
                    }
                });
        }

        public static Task<TimedOperation<List<string>>> GetSongsFromText(string searchString, int amount)
        {
            DateTime startTime = DateTime.Now;
            return WebRequestExtensions.ExecuteJsonWebRequestTask<TimedOperation<List<string>>>(
                string.Format(c_getDirectLinkFormat, amount, searchString, c_youTubeDeveloperKey),
                ytresult =>
                {
                    TimeSpan runTime = DateTime.Now - startTime;
                    try
                    {
                        List<string> results = new List<string>();
                        var entries = ytresult["feed"]["entry"];
                        foreach (var entry in entries)
                        {
                            results.Add(entry["link"][0]["href"]);
                        }
                        return new TimedOperation<List<string>>(results, runTime);
                    }
                    catch
                    {
                        return new TimedOperation<List<string>>(null, runTime);
                    }
                });
        }
    }
}
